//
//  UINavigationBar.swift
//  LLBBaseVC
//
//  Created by Yun on 2018/11/14.
//

import UIKit
import SnapKit
// MARK: - ⚠️方法一
extension UINavigationBar {
    // MARK: - RunTime
    private struct NavigationBarKeys {
        static var overlayKey = "overlayKey"
    }
    
    var overlay: UIView? {
        get {
            return objc_getAssociatedObject(self, &NavigationBarKeys.overlayKey) as? UIView
        }
        set {
            objc_setAssociatedObject(self, &NavigationBarKeys.overlayKey, newValue as UIView?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
        }
    }
    
    // MARK: - 接口
    func LLB_setBackgroundColor(backgroundColor: UIColor) {
        if overlay == nil {
            self.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            overlay = UIView.init(frame: CGRect.init(x: 0, y: 0, width: bounds.width, height: bounds.height))
            overlay?.isUserInteractionEnabled = false
            overlay?.autoresizingMask = UIView.AutoresizingMask.flexibleWidth
        }
        overlay?.backgroundColor = backgroundColor
        let v = subviews.first
        if v != nil{
            v?.insertSubview(overlay!, at: 0)
        }else{
            self.insertSubview(overlay!, at: 0)
        }
        overlay?.snp.remakeConstraints({ (make) in
            make.leading.trailing.bottom.top.equalTo(0)
        })
        
        self.shadowImage = UIImage()
    }
    
    
    func LLB_setTranslationY(translationY: CGFloat) {
        transform = CGAffineTransform.init(translationX: 0, y: translationY)
    }
    
    func LLB_setElementsAlpha(alpha: CGFloat) {
        overlay?.alpha = alpha
        self.backgroundColor = UIColor.clear
        self.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = UIColor.clear
    }
    
    /// viewWillDisAppear调用
    func LLB_reset() {
        setBackgroundImage(nil, for: UIBarMetrics.default)
        overlay?.removeFromSuperview()
        overlay = nil
    }
}
